package com.xs.langchain4j_springboot.controller;


import com.xs.langchain4j_springboot.DTO.ChatRequest;
import okhttp3.MediaType;

import okhttp3.Request;
import okhttp3.OkHttpClient;
import okhttp3.Response;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.*;

import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

@RestController
@RequestMapping("/api/v1")
public class RagFlowController {

    private final OkHttpClient client = new OkHttpClient();
    private static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
    private static final String RAGFLOW_URL = "http://localhost:9222/api/v1/chats/3f631c524cdd11f0b82f7adc79d73497/completions";
    private static final String API_KEY = "ragflow-UxMWQ5MjFlNGNlZDExZjBiODJmN2FkYz";
    private final ExecutorService executor = Executors.newCachedThreadPool();//3f631c524cdd11f0b82f7adc79d73497。    24b8d428467a4c2091e3c3076948c82c

    @GetMapping(value = "/ragFlow",produces ="text/event-stream;charset=UTF-8")
    @CrossOrigin(origins = "*")
    public SseEmitter chatCompletion(      @RequestParam String question,
                                             @RequestParam boolean stream,
                                             @RequestParam String session_id) throws IOException {
        SseEmitter emitter = new SseEmitter(60_000L); // 设置超时时间

/*        request.setSession_id("24b8d428467a4c2091e3c3076948c82c");
        request.setStream(true);*/
        // 构建 JSON 请求体
        String jsonBody = "{"
                + "\"question\":\"" + question + "\","
                + "\"stream\":\"" + stream + "\","
                + "\"session_id\":\"" + session_id + "\""
                + "}";

        // 将字符串转换为字节数组
        byte[] jsonBytes = jsonBody.getBytes(StandardCharsets.UTF_8);

        // 使用 MediaType 和字节数组创建 RequestBody
        okhttp3.RequestBody body = okhttp3.RequestBody.create(JSON,jsonBytes);

        Request httpRequest = new Request.Builder()
                .url(RAGFLOW_URL)
                .post(body)
                .addHeader("Authorization", "Bearer " + API_KEY)
                .build();

        System.out.println("开始请求 ragflow 接口...");
        System.out.println("请求体: {}"+ jsonBody);
        System.out.println("请求url: {}"+ httpRequest.url());

        // 异步执行 OkHttp 请求
        executor.submit(() -> {
            try (Response response = client.newCall(httpRequest).execute()) {
                if (response.isSuccessful()) {
                    String responseBody = response.body().string();

                    // 打印响应体
                    System.out.println("Response Body: " + responseBody);

                    // 发送给前端
                    emitter.send(SseEmitter.event().name("data").data(responseBody));
                } else {
                    System.err.println("请求失败，状态码：" + response.code());
                    emitter.send(SseEmitter.event().name("error").data("Response failed: " + response.code()));
                }
            } catch (IOException e) {
                try {
                    emitter.send(SseEmitter.event().name("error").data("Error: " + e.getMessage()));
                } catch (IOException ex) {
                    throw new RuntimeException(ex);
                }
            } finally {
                emitter.complete();
            }
        });

        return emitter;
    }
}
